<template>
	<view class="history-container">
		<!-- 顶部固定栏 -->
		<view class="header-sticky">
			<view class="header">
				<view class="header-left">
					<text class="iconfont icon-ticket"></text>
					<text class="title">历史排队记录</text>
				</view>
				<view class="header-ctrl">
				<button class="back-btn" @tap="uni.navigateBack()">返回</button>
				</view>
			</view>
		</view>

		<!-- 统计卡片（简版） -->
		<view class="stats-container">
			<view class="stat-card">
				<text class="label">已删除/完成</text>
				<text class="value">{{ total }}</text>
			</view>
		</view>

		<!-- ============== 筛选栏：类型 + 日期 + 搜索按钮 ============== -->
		<view class="filter-bar">
		  <picker mode="selector" :range="typeDisplayOptions" @change="onTypeChange">
		  	<view class="picker-btn">{{ typeLabel }}</view>
		  </picker>
		
		  <picker mode="date" :value="selDate" @change="onDateChange">
		    <view class="picker-btn">日期: {{ selDate }}</view>
		  </picker>
		
		  <button class="search-btn" @tap="onSearch">搜索</button>
		</view>

		<!-- 列表 -->
		<scroll-view scroll-y class="queue-list" refresher-enabled :refresher-triggered="refreshing"
			@refresherrefresh="onRefresh" @scrolltolower="loadMore">
			<view v-for="item in rows" :key="item.id" class="queue-item">
				<!-- 勾选占位（历史页不需要勾选，可留空保持对齐） -->
				<view class="check-placeholder"></view>

				<!-- 横向信息区 -->
				<view class="info-horizontal">
					<text class="info-code">{{ item.code }}</text>
					<text class="info-time">{{ formatTime(item.createdOn) }}</text>
					<text class="info-phone">{{ item.userName ? item.userName : item.phone }}</text>
					<text class="info-phone">用餐{{ item.consumerNum }}人</text>
					<!-- <text class="info-wait">等待{{ getWaitTime(item.createdOn) }}</text> -->
					<text class="info-alarm">叫号{{ item.alarmTimes }}次</text>
				</view>

				<!-- 右侧状态标签（无操作按钮，用标签展示最终状态） -->
				<view class="btn-group">
					<text class="status-tag" :class="'status-' + item.status">
						{{ ['排队中','叫号中','已取消','已超时','已完成'][item.status] }}
					</text>
				</view>
			</view>

			<view v-if="loading" class="load-more">加载中…</view>
			<view v-if="!hasMore && !loading && rows.length" class="load-more">没有更多了</view>
		</scroll-view>

		<!-- ============== 底部分页栏 ============== -->
		<view class="page-bar">
		  <button class="page-btn" :disabled="pageNum===1" @tap="goFirst">首页</button>
		  <button class="page-btn" :disabled="pageNum===1" @tap="goPrev">上一页</button>
		  <text class="page-info">{{ pageNum }} / {{ maxPage }}</text>
		  <button class="page-btn" :disabled="pageNum===maxPage" @tap="goNext">下一页</button>
		  <button class="page-btn" :disabled="pageNum===maxPage" @tap="goLast">末页</button>
		</view>

	</view>
</template>

<script>
	const fmtDate = () => {
		const d = new Date();
		return `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, '0')}${String(d.getDate()).padStart(2, '0')}`;
	};

	export default {
		data() {
			return {
				shopId: '',
				typeOptions: ['全部类型', 'A类', 'B类', 'C类', 'small', 'medium', 'large'],
				typeDisplayOptions: ['全部类型', '小桌', '中桌', '大桌'],
				typeFilter: 'all',
				pageNum: 1,
				pageSize: 10,
				total: 0,
				rows: [],
				loading: false,
				refreshing: false,
				hasMore: true,
				selDate: '', //  yyyy-MM-dd 格式
				maxPage: 1 //  计算总页数
			};
		},
		computed: {
			statusLabel() {
				const idx = this.statusFilter === 'all' ? 0 : this.statusFilter + 1
				return this.statusOptions[idx]
			},
			typeLabel() {
				const map = {
					all: 0,
					A: 1,
					B: 2,
					C: 3,
				}
				return this.typeDisplayOptions[map[this.typeFilter]]
			}
		},
		onLoad(option) {
		  plus.screen.lockOrientation('landscape-primary');
		  this.shopId = option.shopId || '';
		  this.selDate = this.fmtDate(new Date()); // 默认今天
		  this.fetchData('refresh');
		},
		methods: {
		  /* ------ 日期选择 ------ */
		  onDateChange(e) {
		    this.selDate = e.detail.value;          // 保持 yyyy-MM-dd
			console.log(this.selDate);
		    this.pageNum = 1;
		    this.fetchData('refresh');
		  },
		  /* ------ 搜索按钮（统一入口） ------ */
		  onSearch() {
		    this.pageNum = 1;
		    this.fetchData('refresh');
		  },
		  /* ------ 分页按钮（均清空旧数据） ------ */
		  goNext() {
		    if (this.pageNum >= this.maxPage) return;
		    this.pageNum++;              // ① 先 +1
		    this.fetchData('page');    // ② 走 append，不重置页码
		  },
		  goPrev() {
		    if (this.pageNum <= 1) return;
		    this.pageNum--;
		    this.fetchData('page');
		  },
		  goFirst() {
		    this.pageNum = 1;
		    this.fetchData('page');   // 首页才刷新
		  },
		  goLast() {
		    this.pageNum = this.maxPage;
		    this.fetchData('page');    // 末页也 append，避免重复清空
		  },
		  /* ------ 拉取数据（自带清空） ------ */
		  async fetchData(action = 'page') {
		    if (action === 'refresh') {
		      this.refreshing = true;
		      this.pageNum = 1;
		    } else {
		      this.loading = true;
		    }
		  
		    // 清空旧数据（关键）
		    this.rows = [];
		  
		    const params = {
		      PageIndex: this.pageNum,
		      PageSize: this.pageSize,
		      ShopId: this.shopId,
		      Date: this.selDate.replace(/-/g, ''),
		      Type: this.typeFilter === 'all' ? '' : this.typeFilter,
		      IsDeleted: 1
		    };
		  
		    const { data } = await uni.request({
		      url: 'http://ziyan.xshhotels.cn:8981/api/QueueFront/PagingQueue',
		      method: 'GET',
		      data: params
		    });
		  
		    this.parseRes(data, action);
		    this.refreshing = false;
		    this.loading = false;
		  },
		  
			  parseRes(res, action) {
			    const { total, rows } = res;
			    this.total = total;
			    this.maxPage = Math.ceil(total / this.pageSize) || 1;
			  
			    // 无论 refresh 还是 append，都直接替换当前页数据
			    this.rows = rows;
			  
			    this.hasMore = this.rows.length < total;
			  },
			  /* 工具函数 */
			  fmtDate(d) {
			    return `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, '0')}${String(d.getDate()).padStart(2, '0')}`;
			  },
			
			onRefresh() {
				this.fetchData('refresh');
			},
			loadMore() {
				if (this.hasMore && !this.loading) {
					this.pageNum++;
					this.fetchData('append');
				}
			},
			onTypeChange(e) {
				// 更新类型映射：0=全部，1=小桌(A)，2=中桌(B)，3=大桌(C)
				const map = ['all', 'A', 'B', 'C']
				this.typeFilter = map[e.detail.value]
				this.fetchData('refresh')
			},
			formatTime(iso) {
				const d = new Date(iso);
				return `${d.getMonth() + 1}/${d.getDate()} ${d.getHours()}:${d.getMinutes().toString().padStart(2, '0')}`;
			},
			getWaitTime(iso) {
				const min = Math.floor((Date.now() - new Date(iso).getTime()) / 1000 / 60);
				if (min < 1) return '刚刚';
				if (min < 60) return `${min}分钟`;
				const h = Math.floor(min / 60);
				return `${h}小时${min % 60}分钟`;
			}
		}
	};
</script>

<style scoped>
	/* 搜索按钮样式 */
	.search-btn {
	    background: linear-gradient(135deg, #069c29 0%, #047d20 100%);
	    color: #ffffff;
	    padding: 20rpx 32rpx;
	    border-radius: 50rpx;
	    font-size: 30rpx;
	    margin-left: auto;
	    box-shadow: 0 2px 8px rgba(6, 156, 41, 0.2);
	    transition: all 0.2s;
	}
	
	.search-btn:active {
	    background: #046b1c;
	    transform: scale(0.98);
	}
	
	/* 底部分页栏样式 */
	.page-bar {
	    position: fixed;
	    bottom: 0;
	    left: 0;
	    right: 0;
	    background-color: #fff;
	    display: flex;
	    align-items: center;
	    justify-content: space-between;
	    padding: 20rpx 40rpx;
	    box-shadow: 0 -2rpx 10rpx rgba(6, 156, 41, 0.1);
	    z-index: 998;
	}
	
	.page-btn {
	    background: #069c29;
	    color: #ffffff;
	    padding: 12rpx 24rpx;
	    border-radius: 50rpx;
	    font-size: 28rpx;
	    transition: all 0.2s;
	}
	
	.page-btn:active {
	    background: #046b1c;
	    transform: scale(0.96);
	}
	
	.page-btn[disabled] {
	    background-color: #a5d9b1;
	}
	
	.page-info {
	    font-size: 30rpx;
	    color: #2a7d3a;
	}
	
	/* 基础容器样式 */
	.history-container {
	    padding: 20rpx;
	    background-color: #f5fff7;
	    min-height: 100vh;
	    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
	}
	
	/* 固定头部样式 */
	.header-sticky {
	    position: sticky;
	    top: 0;
	    z-index: 999;
	    background: #069c29;
	    box-shadow: 0 2px 8px rgba(6, 156, 41, 0.2);
	}
	
	.header {
	    display: flex;
	    justify-content: space-between;
	    align-items: center;
	    padding: 24rpx 30rpx;
	    color: #fff;
	}
	
	.header-left {
	    display: flex;
	    align-items: center;
	    gap: 16rpx;
	}
	
	.header-ctrl {
	    display: flex;
	    align-items: center;
	    gap: 16rpx;
	}
	
	.icon-ticket::before {
	    content: '🎫';
	    font-size: 44rpx;
	}
	
	.title {
	    font-size: 38rpx;
	    font-weight: 600;
	    letter-spacing: 1rpx;
	}
	
	.back-btn {
	    background-color: #fff;
	    color: #069c29;
	    padding: 10rpx 20rpx;
	    border-radius: 50rpx;
	    font-size: 28rpx;
	    transition: all 0.2s;
	}
	
	.back-btn:active {
	    background: #f0fcf2;
	    transform: scale(0.98);
	}
	
	/* 统计卡片样式 */
	.stats-container {
	    display: flex;
	    gap: 24rpx;
	    margin: 24rpx 0;
	    padding: 0 24rpx;
	}
	
	.stat-card {
	    flex: 1;
	    background-color: #fff;
	    padding: 30rpx 20rpx;
	    border-radius: 30rpx;
	    text-align: center;
	    box-shadow: 0 4px 12px rgba(6, 156, 41, 0.1);
	    transition: transform 0.3s, box-shadow 0.3s;
	}
	
	.stat-card:active {
	    transform: translateY(-2rpx);
	    box-shadow: 0 6px 16px rgba(6, 156, 41, 0.15);
	}
	
	.label {
	    font-size: 28rpx;
	    color: #2a7d3a;
	    display: block;
	    margin-bottom: 12rpx;
	}
	
	.value {
	    font-size: 52rpx;
	    font-weight: 700;
	    color: #047d20;
	    line-height: 1.2;
	}
	
	/* 筛选栏样式 */
	.filter-bar {
	    display: flex;
	    gap: 24rpx;
	    margin-bottom: 24rpx;
	    padding: 0 24rpx;
	}
	
	.picker-btn {
	    flex: 1;
	    background-color: #fff;
	    padding: 22rpx;
	    border-radius: 50rpx;
	    text-align: center;
	    font-size: 30rpx;
	    color: #2a7d3a;
	    box-shadow: 0 2px 6px rgba(6, 156, 41, 0.1);
	    transition: all 0.2s;
	    border: 2px solid #e0fce3;
	}
	
	.picker-btn:active {
	    background: #f0fcf2;
	    color: #069c29;
	    border-color: #a5d9b1;
	}
	
	/* 列表区域样式 */
	.queue-list {
	    height: calc(100vh - 460rpx);
	    background-color: #f5fff7;
	}
	
	.queue-item {
	    display: flex;
	    align-items: center;
	    background-color: #fff;
	    padding: 24rpx;
	    margin: 0 24rpx 20rpx;
	    border-radius: 30rpx;
	    box-shadow: 0 2px 8px rgba(6, 156, 41, 0.1);
	    transition: transform 0.2s, box-shadow 0.2s;
	}
	
	.queue-item:active {
	    transform: translateY(-1rpx);
	    box-shadow: 0 4px 12px rgba(6, 156, 41, 0.15);
	}
	
	.check-placeholder {
	    width: 40rpx;
	    flex-shrink: 0;
	}
	
	.info-horizontal {
	    flex: 1;
	    display: flex;
	    align-items: center;
	    margin-left: 12rpx;
	    gap: 24rpx;
	    flex-wrap: nowrap;
	    overflow: hidden;
	}
	
	.info-code {
	    font-size: 38rpx;
	    font-weight: 700;
	    min-width: 100rpx;
	    color: #047d20;
	}
	
	.info-time {
	    font-size: 28rpx;
	    color: #2a7d3a;
	    min-width: 140rpx;
	    white-space: nowrap;
	}
	
	.info-phone {
	    font-size: 28rpx;
	    color: #069c29;
	    min-width: 160rpx;
	    white-space: nowrap;
	}
	
	.info-wait {
	    font-size: 28rpx;
	    color: #faad14;
	    min-width: 140rpx;
	    white-space: nowrap;
	}
	
	.info-alarm {
	    font-size: 26rpx;
	    color: #069c29;
	    min-width: 120rpx;
	    white-space: nowrap;
	}
	
	.btn-group {
	    display: flex;
	    align-items: center;
	    gap: 12rpx;
	    flex-shrink: 0;
	}
	
	.status-tag {
	    padding: 8rpx 16rpx;
	    border-radius: 50rpx;
	    font-size: 26rpx;
	    color: #ffffff;
	    white-space: nowrap;
	    transition: all 0.2s;
	}
	
	.status-0 {
	    background-color: #2a7d3a;
	}
	
	.status-1 {
	    background-color: #047d20;
	}
	
	.status-2 {
	    background-color: #069c29;
	}
	
	.status-3 {
	    background-color: #ff0000;
	}
	
	.status-4 {
	    background-color: #069c29;
	}
	
	.load-more {
	    text-align: center;
	    padding: 30rpx;
	    font-size: 28rpx;
	    color: #2a7d3a;
	}

</style>